package cn.jtcoding.user.service.impl;

import cn.jtcoding.user.api.UserService;
import cn.jtcoding.user.mapper.UsersMapper;
import cn.jtcoding.user.pojo.bo.UserBO;
import cn.jtcoding.user.pojo.dataobject.UsersDO;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author jason.tang
 * @date 2021/4/2 11:08
 * @desc
 */

@Service
public class UserServiceImpl implements UserService {

    private static final String USER_FACE = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private Sid sid;

    @Override
    public boolean verifyUsernameIsExists(String username) {
        return usersMapper.verifyUsernameIsExists(username);
    }

    @Override
    public UsersDO createUser(UserBO userBO) {
        if (StringUtils.isBlank(userBO.getPassword()) || StringUtils.isBlank(userBO.getConfirmPassword())) {
            throw new ApiException("password cannot be empty.");
        }
        if (!Objects.equals(userBO.getPassword(), userBO.getConfirmPassword())) {
            throw new ApiException("incorrect password.");
        }
        UsersDO users = new UsersDO();
        users.setUsername(userBO.getUsername());
        users.setPassword(userBO.getPassword());
        users.setFace(USER_FACE);
        users.setCreatedTime(LocalDateTime.now());
        users.setUpdatedTime(LocalDateTime.now());
        users.setId(sid.nextShort());
        usersMapper.addUser(users);
        return users;
    }

    @Override
    public UsersDO login(UserBO userBO) {
        UsersDO users = usersMapper.getUser(userBO.getUsername(), userBO.getPassword());
        users.setPassword(null);
        users.setRealname(null);
        users.setMobile(null);
        users.setEmail(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        // TODO 同步购物车商品
        return users;
    }

}
